package org.goldfish.chatroom.controller;

import org.apache.logging.log4j.Logger;
import org.goldfish.chatroom.entity.Message;
import org.goldfish.chatroom.intercepter.LogInterceptor;
import org.goldfish.chatroom.mapper.MessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/")
public class IndexController {
    @Autowired
    private MessageMapper messageMapper;
    private static final Logger logger = org.apache.logging.log4j.LogManager.getLogger(IndexController.class);


    @GetMapping
    public String index(Model model,
                        @RequestParam(
                                name = "password_prompt",
                                defaultValue = "Please enter your password to login")
                        String password_prompt,
                        @RequestParam(
                                name = "autofill",
                                defaultValue = ""
                        )
                        String autofill
    ) {
        model.addAttribute("messages", messageMapper.getMessages());
        model.addAttribute("password_prompt", password_prompt);
        model.addAttribute("autofill", autofill);
        return "index";
    }


    @PostMapping
    public String send_message(
            Model model,
            HttpServletRequest request,
            @RequestParam(name = "message") String content
    ) {
        String username = request.getRemoteAddr(); // Get the sender's IP address
        try {
            Message message = new Message();
            message.setSender(username);
            message.setContent(content);
            message.setTime(new java.sql.Timestamp(System.currentTimeMillis()));
            messageMapper.insertMessage(message);
            return index(model, "Please enter your password to login","");
        } catch (Exception e) {
            logger.warn("Failed to send message", e);
            model.addAttribute("error", e.getLocalizedMessage());
            return "error";
        }
    }


}
